package cn.edu.ncu.housinghub.controller.oss;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.service.impl.OSSService;
import cn.edu.ncu.housinghub.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor
public class OSSController {
    private final OSSService ossService;

    @PostMapping("/upload/propertyImages")
    public Result upload(@RequestParam("file") MultipartFile file) {
        // 1. 获取原始文件名（如 "image.png"）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(".")) {
            // 若文件名无效（无后缀），返回错误
            throw new BusinessException(ErrorCodeConstant.FILE_UPLOAD_ERROR);
        }

        // 2. 提取文件后缀（如 "png"）
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 3. 验证是否为图片格式（可选，增强安全性）
        String[] allowedSuffix = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        boolean isImage = Arrays.asList(allowedSuffix).contains(suffix.toLowerCase());
        if (!isImage) {
            throw new  BusinessException(ErrorCodeConstant.FILE_UPLOAD_IMAGE_TYPE_ERROR);
        }

        // 4. 生成图片路径（如 "images/xxx.png"）
        String filePath = "images/" + UUID.randomUUID() + suffix;

        // 5. 上传并返回结果
        return Result.success(ossService.uploadFile(file, filePath));
    }

    @PostMapping("/upload/contractPDfs")
    public Result uploadPdf(@RequestParam("file") MultipartFile file) {
        // 1. 获取原始文件名（如 "document.pdf"）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(".")) {
            // 文件名无效（无后缀）
            throw new BusinessException(ErrorCodeConstant.FILE_UPLOAD_ERROR);
        }

        // 2. 提取文件后缀（如 ".pdf"）
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 3. 验证是否为PDF格式
        if (!".pdf".equalsIgnoreCase(suffix)) {
            throw new BusinessException(ErrorCodeConstant.FILE_UPLOAD_PDF_TYPE_ERROR);
        }


        String filePath = "pdfs/" + UUID.randomUUID() + ".pdf";

        // 5. 上传并返回结果
        return Result.success(ossService.uploadFile(file, filePath));
    }
}
